package com.cskaoyan.gateway.controller.order;

import com.alibaba.fastjson.JSON;
import com.mall.commons.result.ResponseData;
import com.mall.commons.result.ResponseUtil;
import com.mall.order.OrderCoreService;
import com.mall.order.OrderQueryService;
import com.mall.order.constant.OrderRetCode;
import com.mall.order.dto.*;
import com.cskaoyan.gateway.form.order.OrderDetail;
import io.swagger.annotations.Api;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import static com.mall.user.intercepter.TokenIntercepter.USER_INFO_KEY;

/**
 * 订单控制层
 * @author Javid Xi
 * @version 1.0
 * @since 2021/7/22
 */
@RestController
@RequestMapping("/shopping")
@Api(tags = "CartController", description = "订单控制层")
public class OrderController {

    @Reference(timeout = 4000,check = false)
    private OrderQueryService orderQueryService;
    @Reference(timeout = 4000,check = false)
    private OrderCoreService orderCoreService;

    /**
     * 创建订单
     * @param request 请求参数
     * @param httpRequest http请求
     * @return ResponseData
     */
    @PostMapping("/order")
    public ResponseData<?> order(@RequestBody CreateOrderRequest request, HttpServletRequest httpRequest){
        // 获取用户id
        String userInfo = (String) httpRequest.getAttribute(USER_INFO_KEY);
        Map<String,Object> parse = (Map<String, Object>) JSON.parse(userInfo);
        Long userId = Long.valueOf(parse.get("uid").toString());
        request.setUserId(userId);

        // 生成uuid
        request.setUniqueKey(UUID.randomUUID().toString().replace("-", ""));
        // 创建订单
        CreateOrderResponse response = orderCoreService.createOrder(request);
        if(OrderRetCode.SUCCESS.getCode().equals(response.getCode()))
            return new ResponseUtil<>().setData(response.getOrderId());
        return new ResponseUtil<>().setErrorMsg(response.getMsg());
    }

    /**
     * 取消订单
     * @param map 请求参数
     * @return ResponseData
     */
    @PostMapping("/cancelOrder")
    public ResponseData<?> cancelOrder(@RequestBody Map<String, String> map) {
        CancelOrderRequest cancelOrderRequest = new CancelOrderRequest();
        cancelOrderRequest.setOrderId(map.get("orderId"));

        CancelOrderResponse response = orderCoreService.cancelOrder(cancelOrderRequest);
        if (OrderRetCode.SUCCESS.getCode().equals(response.getCode()))
            return new ResponseUtil<>().setData(response.getMsg());
        return new ResponseUtil<>().setErrorMsg(response.getMsg());
    }

    /**
     * 删除订单
     * @param orderId 订单id
     * @return ResponseData
     */
    @DeleteMapping("/order/{id}")
    public ResponseData<?> deleteOrder(@PathVariable("id") String orderId) {
        // 封装请求
        DeleteOrderRequest deleteOrderRequest = new DeleteOrderRequest();
        deleteOrderRequest.setOrderId(orderId);
        // 删除订单
        DeleteOrderResponse response = orderCoreService.deleteOrder(deleteOrderRequest);

        if (OrderRetCode.SUCCESS.getCode().equals(response.getCode()))
            return new ResponseUtil<>().setData(response.getMsg());
        return new ResponseUtil<>().setErrorMsg(response.getMsg());
    }

    /**
     * 查看订单详情
     * @param orderId 订单id
     * @return ResponseData
     */
    @GetMapping("/order/{id}")
    public ResponseData<?> orderDetail(@PathVariable("id") String orderId){
        // 封装请求
        OrderDetailRequest request = new OrderDetailRequest();
        request.setOrderId(orderId);
        // 查询
        OrderDetailResponse response = orderQueryService.orderDetail(request);

        if (OrderRetCode.SUCCESS.getCode().equals(response.getCode())) {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderTotal(response.getPayment());
            orderDetail.setUserId(response.getUserId());
            orderDetail.setUsername(response.getBuyerNick());
            orderDetail.setGoodsList(response.getOrderItemDto());
            orderDetail.setTel(response.getOrderShippingDto().getReceiverPhone());
            orderDetail.setStreetName(response.getOrderShippingDto().getReceiverAddress());
            orderDetail.setOrderStatus(response.getStatus());
            return new ResponseUtil<>().setData(orderDetail);
        }
        return new ResponseUtil<>().setErrorMsg(response.getMsg());
    }

    /**
     * 分页获取当前用户所有订单
     * @param page 页码
     * @param size 页大小
     * @param request 请求
     * @return ResponseData
     */
    @GetMapping("/order")
    public ResponseData<?> orderList(Integer page, Integer size, HttpServletRequest request){
        // 获取用户id
        String userInfo = (String) request.getAttribute(USER_INFO_KEY);
        Map<String,Object> parse = (Map<String, Object>) JSON.parse(userInfo);
        Long userId = Long.valueOf(parse.get("uid").toString());
        // 封装请求
        OrderListRequest orderListRequest = new OrderListRequest();
        orderListRequest.setUserId(userId);
        orderListRequest.setSort("create_time"); // 根据创建时间排序
        orderListRequest.setPage(page);
        orderListRequest.setSize(size);
        // 查询
        OrderListResponse response = orderQueryService.orderList(orderListRequest);

        if (response.getCode().equals(OrderRetCode.SUCCESS.getCode())) {
            HashMap<String, Object> map = new HashMap<String, Object>(){{
                put("data", response.getDetailInfoList());
                put("total", response.getTotal());
            }};
            return new ResponseUtil<>().setData(map);
        }
        return new ResponseUtil<>().setErrorMsg(response.getMsg());
    }
}
